import React from 'react';
import { Layout, notification } from 'antd';
import NProgress from 'nprogress';
import DocumentTitle from 'react-document-title';
import isEqual from 'lodash/isEqual';
import memoizeOne from 'memoize-one';
import { connect } from 'dva';
import { ContainerQuery } from 'react-container-query';
import classNames from 'classnames';
import pathToRegexp from 'path-to-regexp';
import { enquireScreen, unenquireScreen } from 'enquire-js';
import { formatMessage } from 'umi/locale';
import SiderMenu from '@/components/SiderMenu';
import Authorized from '@/utils/Authorized';
import SettingDrawer from '@/components/SettingDrawer';
// import logo from '../assets/logo.svg';
import Footer from './Footer';
import Header from './Header';
import Context from './MenuContext';
import Exception403 from '../pages/Exception/403';

const logo = 'http://www.liangzivip.com:8088/skin/default/logo.png';
const { Content } = Layout;

// Conversion router to menu.
function formatter(data, parentAuthority, parentName) {
  return data
    .map(item => {
      if (!item.name || !item.path) {
        return null;
      }

      let locale = 'menu';
      if (parentName) {
        locale = `${parentName}.${item.name}`;
      } else {
        locale = `menu.${item.name}`;
      }

      const result = {
        ...item,
        name: formatMessage({ id: locale, defaultMessage: item.name }),
        locale,
        authority: item.authority || parentAuthority,
      };
      if (item.routes) {
        const children = formatter(item.routes, item.authority, locale);
        // Reduce memory usage
        result.children = children;
      }
      delete result.routes;
      return result;
    })
    .filter(item => item);
}

const memoizeOneFormatter = memoizeOne(formatter, isEqual);

const query = {
  'screen-xs': {
    maxWidth: 575,
  },
  'screen-sm': {
    minWidth: 576,
    maxWidth: 767,
  },
  'screen-md': {
    minWidth: 768,
    maxWidth: 991,
  },
  'screen-lg': {
    minWidth: 992,
    maxWidth: 1199,
  },
  'screen-xl': {
    minWidth: 1200,
    maxWidth: 1599,
  },
  'screen-xxl': {
    minWidth: 1600,
  },
};

let currHref = '';

class BasicLayout extends React.PureComponent {
  constructor(props) {
    super(props);
    this.getPageTitle = memoizeOne(this.getPageTitle);
    this.getBreadcrumbNameMap = memoizeOne(this.getBreadcrumbNameMap, isEqual);
    this.breadcrumbNameMap = this.getBreadcrumbNameMap();
    this.matchParamsPath = memoizeOne(this.matchParamsPath, isEqual);
  }

  state = {
    rendering: true,
    isMobile: false,
    menuData: this.getMenuData(),
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'user/fetchCurrent',
    });
    dispatch({
      type: 'setting/getSetting',
    });
    this.renderRef = requestAnimationFrame(() => {
      this.setState({
        rendering: false,
      });
    });
    this.enquireHandler = enquireScreen(mobile => {
      const { isMobile } = this.state;
      if (isMobile !== mobile) {
        this.setState({
          isMobile: mobile,
        });
      }
    });

    this.loadCommonData();
  }

  componentDidUpdate(preProps) {
    const { loading } = this.props;
    // 浏览器地址栏中地址
    const { href } = window.location;
    // currHref 和 href 不一致时说明进行了页面跳转
    if (currHref !== href) {
      // 页面开始加载时调用 start 方法
      NProgress.start();
      // loading.global 为 false 时表示加载完毕
      if (!loading.global) {
        // 页面请求完毕时调用 done 方法
        NProgress.done();
        // 将新页面的 href 值赋值给 currHref
        currHref = href;
      }
    }

    // After changing to phone mode,
    // if collapsed is true, you need to click twice to display
    this.breadcrumbNameMap = this.getBreadcrumbNameMap();
    const { isMobile } = this.state;
    const { collapsed } = this.props;
    if (isMobile && !preProps.isMobile && !collapsed) {
      this.handleMenuCollapse(false);
    }
  }

  componentWillUnmount() {
    cancelAnimationFrame(this.renderRef);
    unenquireScreen(this.enquireHandler);
  }

  getContext() {
    const { location } = this.props;
    return {
      location,
      breadcrumbNameMap: this.breadcrumbNameMap,
    };
  }

  getMenuData() {
    const {
      route: { routes },
    } = this.props;
    return memoizeOneFormatter(routes);
  }

  /**
   * 获取面包屑映射
   * @param {Object} menuData 菜单配置
   */
  getBreadcrumbNameMap() {
    const routerMap = {};
    const mergeMenuAndRouter = data => {
      data.forEach(menuItem => {
        if (menuItem.children) {
          mergeMenuAndRouter(menuItem.children);
        }
        // Reduce memory usage
        routerMap[menuItem.path] = menuItem;
      });
    };
    mergeMenuAndRouter(this.getMenuData());
    return routerMap;
  }

  matchParamsPath = pathname => {
    const pathKey = Object.keys(this.breadcrumbNameMap).find(key =>
      pathToRegexp(key).test(pathname)
    );
    return this.breadcrumbNameMap[pathKey];
  };

  getPageTitle = pathname => {
    const currRouterData = this.matchParamsPath(pathname);

    if (!currRouterData) {
      return 'Ant Design Pro';
    }
    const message = formatMessage({
      id: currRouterData.locale || currRouterData.name,
      defaultMessage: currRouterData.name,
    });
    return `${message} - Ant Design Pro`;
  };

  getLayoutStyle = () => {
    const { isMobile } = this.state;
    const { fixSiderbar, collapsed, layout } = this.props;
    if (fixSiderbar && layout !== 'topmenu' && !isMobile) {
      return {
        paddingLeft: collapsed ? '80px' : '256px',
      };
    }
    return null;
  };

  getContentStyle = () => {
    const { fixedHeader } = this.props;
    return {
      margin: '24px 24px 0',
      paddingTop: fixedHeader ? 64 : 0,
    };
  };

  loadCommonData = () => {
    const dataLoadQuery = [
      {
        request: 'rank/list',
        handleResponse: props => {
          const {
            rank: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setRank',
        dataname: '产品类型',
      },
      {
        request: 'brand/list',
        handleResponse: props => {
          const {
            brand: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setBrand',
        dataname: '商品品牌',
      },
      {
        request: 'buyType/list',
        handleResponse: props => {
          const {
            buyType: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setBuyType',
        dataname: '售卖渠道',
      },
      {
        request: 'saleType/list',
        handleResponse: props => {
          const {
            saleType: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setSaleType',
        dataname: '销售类型',
      },
      {
        request: 'unit/list',
        handleResponse: props => {
          const {
            unit: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setUnit',
        dataname: '产品单位',
      },
      {
        request: 'productStatus/list',
        handleResponse: props => {
          const {
            productStatus: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setProductStatus',
        dataname: '产品状态',
      },
      {
        request: 'orderType/list',
        handleResponse: props => {
          const {
            orderType: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setOrderType',
        dataname: '订单类型',
      },
      {
        request: 'orderStatus/list',
        handleResponse: props => {
          const {
            orderStatus: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setOrderStatus',
        dataname: '订单状态',
      },
      {
        request: 'payType/list',
        handleResponse: props => {
          const {
            payType: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setPayType',
        dataname: '支付类型',
      },
      {
        request: 'consumerType/list',
        handleResponse: props => {
          const {
            consumerType: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setConsumerType',
        dataname: '消费者类型',
      },
      {
        request: 'city/list',
        handleResponse: props => {
          const {
            city: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setCity',
        dataname: '城市数据',
      },
      {
        request: 'gender/list',
        handleResponse: props => {
          const {
            gender: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setGender',
        dataname: '性别数据',
      },
      {
        request: 'salerStatus/list',
        handleResponse: props => {
          const {
            salerStatus: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setSalerStatus',
        dataname: '服务站状态',
      },
      {
        request: 'deliverRegion/list',
        handleResponse: props => {
          const {
            deliverRegion: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setDeliverRegion',
        dataname: '配送区域',
      },
      {
        request: 'consumerLevel/list',
        handleResponse: props => {
          const {
            consumerLevel: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setConsumerLevel',
        dataname: '用户等级',
      },
      {
        request: 'autonomousAuthority/list',
        handleResponse: props => {
          const {
            autonomousAuthority: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setAutonomousAuthority',
        dataname: '前台管理',
      },
      {
        request: 'transactionNotice/list',
        handleResponse: props => {
          const {
            transactionNotice: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setTransactionNotice',
        dataname: '交易提醒',
      },
      {
        request: 'purchaseAuthority/list',
        handleResponse: props => {
          const {
            purchaseAuthority: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setPurchaseAuthority',
        dataname: '采购权限',
      },
      {
        request: 'shopDisplay/list',
        handleResponse: props => {
          const {
            shopDisplay: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setShopDisplay',
        dataname: '店铺前台显示',
      },
      {
        request: 'shopFee/list',
        handleResponse: props => {
          const {
            shopFee: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setShopFee',
        dataname: '店铺缴费',
      },
      {
        request: 'shopStatus/list',
        handleResponse: props => {
          const {
            shopStatus: { data },
          } = props;
          return data;
        },
        setDataCache: 'global/setShopStatus',
        dataname: '店铺状态',
      },
    ];

    dataLoadQuery.forEach(item => {
      this.locaCommonData(item.request, item.handleResponse, item.setDataCache, item.dataname);
    });
  };

  locaCommonData = (request, handleResponse, setDataCache, dataname = '') => {
    const { dispatch } = this.props;

    dispatch({
      type: request,
      payload: {},
    }).then(() => {
      const data = handleResponse(this.props);

      const { code: statusCode, msg: messageText } = data;

      if (statusCode !== 200) {
        setTimeout(() => {
          notification.error({
            placement: 'bottomRight',
            message: `加载${dataname}数据失败!`,
            description: messageText,
          });
        }, 500);
      } else {
        const { list: listData } = data;

        dispatch({
          type: setDataCache,
          payload: listData || [],
          // }).then(() => {
          //   setTimeout(() => {
          //     notification.info({
          //       placement: 'bottomRight',
          //       message: '数据加载',
          //       description: `获取${dataname}据成功.`,
          //     });
          //   }, 500);
        });
      }
    });
  };

  handleMenuCollapse = collapsed => {
    const { dispatch } = this.props;
    dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
  };

  renderSettingDrawer() {
    // Do not render SettingDrawer in production
    // unless it is deployed in preview.pro.ant.design as demo
    const { rendering } = this.state;
    if ((rendering || process.env.NODE_ENV === 'production') && APP_TYPE !== 'site') {
      return null;
    }
    return <SettingDrawer />;
  }

  render() {
    const {
      navTheme,
      layout: PropsLayout,
      children,
      location: { pathname },
    } = this.props;
    const { isMobile, menuData } = this.state;
    const isTop = PropsLayout === 'topmenu';
    const routerConfig = this.matchParamsPath(pathname);
    const layout = (
      <Layout>
        {isTop && !isMobile ? null : (
          <SiderMenu
            logo={logo}
            Authorized={Authorized}
            theme={navTheme}
            onCollapse={this.handleMenuCollapse}
            menuData={menuData}
            isMobile={isMobile}
            {...this.props}
          />
        )}
        <Layout
          style={{
            ...this.getLayoutStyle(),
            minHeight: '100vh',
          }}
        >
          <Header
            menuData={menuData}
            handleMenuCollapse={this.handleMenuCollapse}
            logo={logo}
            isMobile={isMobile}
            {...this.props}
          />
          <Content style={this.getContentStyle()}>
            <Authorized
              authority={routerConfig && routerConfig.authority}
              noMatch={<Exception403 />}
            >
              {children}
            </Authorized>
          </Content>
          <Footer />
        </Layout>
      </Layout>
    );
    return (
      <React.Fragment>
        <DocumentTitle title={this.getPageTitle(pathname)}>
          <ContainerQuery query={query}>
            {params => (
              <Context.Provider value={this.getContext()}>
                <div className={classNames(params)}>{layout}</div>
              </Context.Provider>
            )}
          </ContainerQuery>
        </DocumentTitle>
        {this.renderSettingDrawer()}
      </React.Fragment>
    );
  }
}

export default connect(
  ({
    global,
    setting,
    rank,
    brand,
    buyType,
    saleType,
    unit,
    productStatus,
    orderType,
    orderStatus,
    payType,
    consumerType,
    city,
    gender,
    salerStatus,
    deliverRegion,
    consumerLevel,
    autonomousAuthority,
    transactionNotice,
    purchaseAuthority,
    shopDisplay,
    shopFee,
    shopStatus,
    loading,
  }) => ({
    collapsed: global.collapsed,
    layout: setting.layout,
    ...setting,
    rank,
    brand,
    buyType,
    saleType,
    unit,
    productStatus,
    orderType,
    orderStatus,
    payType,
    consumerType,
    city,
    gender,
    salerStatus,
    deliverRegion,
    consumerLevel,
    autonomousAuthority,
    transactionNotice,
    purchaseAuthority,
    shopDisplay,
    shopFee,
    shopStatus,
    loading,
  })
)(BasicLayout);
